import type { UserProfile } from '@/services/generated/src/index';

export default (initialState: { currentUser?: UserProfile; userPermissions?: string[]; userGroups?: string[] } | undefined) => {
  // 权限控制 - 使用Django内建权限系统
  // 参考文档 https://umijs.org/docs/max/access

  const currentUser = initialState?.currentUser;
  const userPermissions = initialState?.userPermissions || [];
  const userGroups = initialState?.userGroups || [];

  // 检查用户是否有特定权限 (Django格式: app_label.action_model)
  const hasPermission = (permission: string) => {
    // 超级用户拥有所有权限
    if (currentUser?.is_superuser) return true;
    return userPermissions.includes(permission);
  };

  // 检查用户是否属于特定组
  const hasGroup = (groupName: string) => {
    // 超级用户默认属于所有组
    if (currentUser?.is_superuser) return true;
    return userGroups.includes(groupName);
  };

  // 基础权限检查
  const canSeeAdmin = !!(currentUser && (currentUser.is_staff || currentUser.is_superuser || hasGroup('administrators')));
  const isAuthenticated = !!currentUser;

  // 用户管理权限 (Django内建权限格式)
  const canViewUsers = hasPermission('auth.view_user') || hasGroup('administrators') || hasGroup('managers');
  const canCreateUser = hasPermission('auth.add_user') || hasGroup('administrators') || hasGroup('managers');
  const canUpdateUser = hasPermission('auth.change_user') || hasGroup('administrators') || hasGroup('managers');
  const canDeleteUser = hasPermission('auth.delete_user') || hasGroup('administrators');

  // 组管理权限 (替代原来的角色管理)
  const canViewGroups = hasPermission('auth.view_group') || hasGroup('administrators');
  const canCreateGroup = hasPermission('auth.add_group') || hasGroup('administrators');
  const canUpdateGroup = hasPermission('auth.change_group') || hasGroup('administrators');
  const canDeleteGroup = hasPermission('auth.delete_group') || hasGroup('administrators');

  // 权限管理权限 (只读)
  const canViewPermissions = hasPermission('auth.view_permission') || hasGroup('administrators');

  // 系统管理权限
  const canViewSystem = hasGroup('administrators') || currentUser?.is_superuser;

  return {
    // 基础权限
    canSeeAdmin,
    isAuthenticated,
    hasPermission,
    hasGroup,

    // 用户管理
    canViewUsers,
    canCreateUser,
    canUpdateUser,
    canDeleteUser,

    // 组管理 (替代角色管理)
    canViewGroups,
    canCreateGroup,
    canUpdateGroup,
    canDeleteGroup,

    // 权限管理 (只读)
    canViewPermissions,

    // 系统管理
    canViewSystem,

    // 兼容性别名
    canViewRoles: canViewGroups,
    canCreateRole: canCreateGroup,
    canUpdateRole: canUpdateGroup,
    canDeleteRole: canDeleteGroup,
  };
};
